#include "Game.hpp"
#include "imgui_impl_sdl2.h"
#include "imgui_impl_sdlrenderer2.h"
#include "Systems.hpp"
#include "Components.hpp"
#include "Engine.hpp"

Game::Game(Engine* engine) : engine(engine), inputSystem(nullptr), movementSystem(nullptr)
    , animationSystem(nullptr), renderSystem(nullptr), collisionSystem(nullptr), scriptSystem(nullptr) {

}

Game::~Game() {
    shutdown();
}

bool Game::initialize() {
    renderer = engine->getRenderer();
    if(renderer == nullptr) {
        return false;
    }

    inputSystem = new InputSystem();
    movementSystem = new MovementSystem();
    animationSystem = new AnimationSystem();
    scriptSystem = new ScriptSystem(engine);
    collisionSystem = new CollisionSystem();
    renderSystem = new RenderSystem(renderer);

    return true;
}

void Game::processInput() {
    SDL_Event event;
    while (SDL_PollEvent(&event)) {
        inputSystem->update(event, engine->getRegistry());
        if (inputSystem->shouldQuit()) {
            setQuit();
        }
    }
}

void Game::update(float deltaTime) {
    movementSystem->update(engine->getRegistry(), deltaTime);
    animationSystem->update(engine->getRegistry());
    collisionSystem->update(engine->getRegistry());
    scriptSystem->Update(deltaTime);
}

void Game::render() {
    renderSystem->update(engine->getRegistry());
}

void Game::shutdown() {
    if (inputSystem) {
        delete inputSystem;
        inputSystem = nullptr;
    }

    if (movementSystem) {
        delete movementSystem;
        movementSystem = nullptr;
    }

    if (animationSystem) {
        delete movementSystem;
        movementSystem = nullptr;
    }

    if (scriptSystem) {
        delete scriptSystem;
        scriptSystem = nullptr;
    }

    if (collisionSystem) {
        delete collisionSystem;
        collisionSystem = nullptr;
    }

    if (renderSystem) {
        delete renderSystem;
        renderSystem = nullptr;
    }
}
